package com.sdx.console.banner.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.banner.entity.BaseBanner;
import com.sdx.console.banner.service.BaseBannerService;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.content.entity.ResContentMain;
import com.sdx.console.content.service.ResContentMainService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.orgmain.entity.OrgLecture;
import com.sdx.console.orgmain.service.OrgLectureService;
import com.sdx.console.system.service.DictBusinessService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
 * banner 接口
 */
@RequestMapping("/banner/banner")
@Controller
public class BaseBannerController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(BaseBannerController.class);
    private static final String MODEL = "/banner/banner";


    @Resource
	private BaseBannerService bannerService;

	@Resource
	private ResCloudFileService resCloudFileService;

	@Resource
	private BaseDataService baseDataService;

	@Resource
	private DictBusinessService dictBusinessService;

	@Resource
	private OrgLectureService orgLectureService;

	@Resource
	private ResContentMainService resContentMainService;

	@Resource
	private CustomerInfoService customerInfoService;

	@Resource
	private CoreDictService coreDictService;


	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

		List<DictBusiness> moduleList = dictBusinessService.getModule(2);
		//目标平台输出志愿填报
		List<DictBusiness> dictBusinessList = moduleList.stream().filter(m->m.getDictId().equals(16)/* || m.getDictId().equals(17)*/).collect(Collectors.toList());
		view.addObject("moduleList",dictBusinessList);
		view.addObject("provinceList",baseDataService.getAllProvince());


	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("banner.banner.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("banner.banner.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,String bannerId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        BaseBanner banner = bannerService.queryById(bannerId);
		banner.setDisplyName(banner.getHref());
		String typeId = banner.getType();
		switch (typeId){
			//转到讲座
			case "2":
				banner.setDisplyName(String.valueOf(orgLectureService.queryById(banner.getHref()).getLectureTitle()));
				break;
			//转到资讯
			case "3":
				banner.setDisplyName(String.valueOf(resContentMainService.queryById(banner.getHref()).getContentTitle()));
				break;
			//转到老师
			case "4":
				banner.setDisplyName(String.valueOf(customerInfoService.queryById(banner.getHref()).getCustomerName()));
				break;
			//小程序
			case "5":
				// 小程序类型
				banner.setDisplyName(String.valueOf(coreDictService.findCoreDict("XCX_TYPE",banner.getHref()).getName()));
				break;
		}
        view.addObject("banner", banner);
		setPageParam(view,request);
		try {
			view.addObject("bannerJson", JacksonUtils.toJsonString(banner,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("banner.banner.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("banner.banner.query")
    @ResponseBody
    public JsonResult<PageQuery> list(BaseBanner condtion,HttpServletRequest request)
    {
	    CoreUser user = getLoginUser(request);
	    condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        bannerService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,BaseBanner banner,HttpServletRequest request
							,MultipartFile bannerPathFile,MultipartFile shareImgFile
	) {
    	JsonResult result = JsonResult.success();
	    CoreUser user = getLoginUser(request);
	    banner.setTenantId(user.getTenantId());
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/banner/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(bannerPathFile)) {
			try
			{
		        String bannerPathFileNamePair = FileUtils.upload(subPath,bannerPathFile);
		        String bannerPathStoreFile = bannerPathFileNamePair.split("::")[0];
		        bannerPathStoreFile = subPath+bannerPathStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+bannerPathStoreFile,bucketName,bannerPathStoreFile.substring(1));
				String bannerPathUrl = "https://sdxcomm."+ConfigService.ossDomain+bannerPathStoreFile;
				banner.setBannerPath(bannerPathUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,bannerPathStoreFile,bannerPathUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		if (!FileUtils.isEmptyFile(shareImgFile)) {
			try
			{
				String shareImgFileNamePair = FileUtils.upload(subPath,shareImgFile);
				String shareImgStoreFile = shareImgFileNamePair.split("::")[0];
				shareImgStoreFile = subPath+shareImgStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+shareImgStoreFile,bucketName,shareImgStoreFile.substring(1));
				String shareImgUrl = "https://sdxcomm."+ConfigService.ossDomain+shareImgStoreFile;
				banner.setShareImg(shareImgUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,shareImgStoreFile,shareImgUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}

    	if (isNew) {
//			banner.setCreatedBy(user.getId().intValue());
//			banner.setCreatedName(user.getName());
//			banner.setUpdatedBy(user.getId().intValue());
//			banner.setUpdatedName(user.getName());
//			banner.setUpdatedTime(new Date());
			banner.setCreatedTime(new Date());
			bannerService.save(banner);
		} else {
//			banner.setUpdatedBy(user.getId().intValue());
//			banner.setUpdatedName(user.getName());
//			banner.setUpdatedTime(new Date());
			bannerService.updateTemplate(banner);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("banner.banner.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)BaseBanner banner,HttpServletRequest request
							,@RequestParam("bannerPathFile") MultipartFile bannerPathFile
							,@RequestParam("shareImgFile") MultipartFile shareImgFile
		)
    {

        return save(true,banner,request
					,bannerPathFile,shareImgFile
		);
    }

    @PostMapping("/update.json")
    @Function("banner.banner.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  BaseBanner banner,HttpServletRequest request
							,@RequestParam("bannerPathFile") MultipartFile bannerPathFile
			,@RequestParam("shareImgFile") MultipartFile shareImgFile
		) {
		return save(false,banner,request
		,bannerPathFile,shareImgFile
		);
    }



    @GetMapping("/view.json")
    @Function("banner.banner.query")
    @ResponseBody
    public JsonResult<BaseBanner>queryInfo(String bannerId) {
        BaseBanner banner = bannerService.queryById( bannerId);
        return  JsonResult.success(banner);
    }

    @PostMapping("/delete.json")
    @Function("banner.banner.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        bannerService.batchDelBaseBanner(idList);
        return JsonResult.success();
    }

	/* ajax json */

	@GetMapping("/dataList.json")
	@Function("banner.banner.query")
	@ResponseBody
	public JsonResult dataList(String typeId, String provinceId)
	{


		switch (typeId){
		   	//转到讲座
			case "2":
				List<OrgLecture> orgLectureList = orgLectureService.queryByProvinceId(provinceId);
				List<Map> mapList = new ArrayList<>();
				for (OrgLecture orgLecture:orgLectureList) {
					Map map = new HashMap();
					map.put("id",orgLecture.getLectureId());
					map.put("name",orgLecture.getLectureTitle());
					mapList.add(map);
				}
				return JsonResult.success(mapList);
			//转到资讯
			case "3":
				List<ResContentMain> resContentMainList = resContentMainService.queryByProvinceId(provinceId);
				List<Map> mapList2 = new ArrayList<>();
				for (ResContentMain resContentMain:resContentMainList) {
					Map map2 = new HashMap();
					map2.put("id",resContentMain.getContentId());
					map2.put("name",resContentMain.getContentTitle());
					mapList2.add(map2);
				}
				return JsonResult.success(mapList2);
			//转到老师
			case "4":
				CustomerInfo customerInfo = new CustomerInfo();
				customerInfo.setIsTeacher(1);
				List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
				List<Map> mapList3 = new ArrayList<>();
				for (CustomerInfo customerInfo1:customerInfoList) {
					Map map3 = new HashMap();
					map3.put("id",customerInfo1.getCustomerId());
					map3.put("name",customerInfo1.getCustomerName());
					mapList3.add(map3);
				}
				return JsonResult.success(mapList3);

			//转到老师
			case "5":
				// 小程序类型
				List<CoreDict> serviceTypeList = coreDictService.findAllByType("XCX_TYPE");
				List<Map> mapList4 = new ArrayList<>();
				for (CoreDict coreDict:serviceTypeList) {
					Map map4 = new HashMap();
					map4.put("id",coreDict.getValue());
					map4.put("name",coreDict.getName());
					mapList4.add(map4);
				}
				return JsonResult.success(mapList4);
			case "7":
				// 小程序类型
				List<BaseEntity> saleProduct = bannerService.selectSaleProduct();
//				List<Map> mapList4 = new ArrayList<>();
//				for (CoreDict coreDict:serviceTypeList) {
//					Map map4 = new HashMap();
//					map4.put("id",coreDict.getValue());
//					map4.put("name",coreDict.getName());
//					mapList4.add(map4);
//				}
//				return JsonResult.success(mapList4);
				return JsonResult.success(saleProduct);
		}
		return JsonResult.fail();
	}



}
